
let express = require('express')
let app = express()

let bodyParser = require('body-parser')
let cors = require('cors')
let router = require('./router')
const session = require('express-session')
const jwt = require('jsonwebtoken')
const { expressjwt } = require('express-jwt')
const secretKey = 'GSX No1 ^_^'
const port = 5000
app.use(bodyParser.json());  //配置解析，用于解析json和urlencoded格式的数据
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors())              //配置跨域，必须在路由之前
app.use(
    session({            //身份验证
        secret: 'GSX No1 ^_^',
        resave: false,
        saveUninitialized: true
    })
)

app.use(
    expressjwt({
        secret: secretKey,
        algorithms: ["HS256"],
    })
        .unless({ path: [/^\/user\/.*/, /^\/public\/.*/] })
)
app.use(router)              //路由引用
app.use('/public', express.static('./public'))
// expressjwt过期的错误中间件
app.use((err, req, res, next) => {
    // 这次错误是由 token 解析失败导致的
    if (err.name === 'UnauthorizedError') {
        return res.send({
            status: 401,
            message: '无效的token',
        })
    }
    res.send({
        status: 500,
        message: '未知的错误',
    })
})




app.listen(port, () => {
    console.log(`http://localhost:${port}`);
})
